package com.treasure.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.treasure.common.enums.SmsUsageEnum;
import com.treasure.common.types.EmailAddress;
import com.treasure.common.types.PhoneNumber;
import com.treasure.common.types.VerifyCode;
import com.treasure.domain.domain.MessageSenderDomainService;
import com.treasure.domain.domain.entity.EmailMessage;
import com.treasure.domain.domain.entity.document.SmsMessage;
import com.treasure.infrastructure.model.po.SmsVerifyCodeInfo;
import com.treasure.infrastructure.repository.dao.mapper.SmsVerifyCodeInfoMapper;
import com.treasure.web.service.SmsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Random;

/**
 * @author sunhongmin
 * @date 2023/9/13 21:39
 * @description
 */
@Service
@RequiredArgsConstructor
public class SmsServiceImpl implements SmsService {
    private final SmsVerifyCodeInfoMapper smsVerifyCodeInfoMapper;
    private final MessageSenderDomainService messageSenderDomainService;

    @Override
    public void sendVerifyCode(PhoneNumber phoneNumber, SmsUsageEnum smsUsage) throws IOException {
        messageSenderDomainService.sendSmsMessage(new SmsMessage(phoneNumber.getValue()), smsUsage);
    }

    @Override
    public void sendEmailVerifyCode(String invitationCode, EmailAddress emailAddress, SmsUsageEnum smsUsage) throws IOException {
        messageSenderDomainService.sendEmailMessage(invitationCode, new EmailMessage(emailAddress.getValue()), smsUsage);
    }

    @Override
    public SmsVerifyCodeInfo getVerifyInfo(PhoneNumber phoneNumber, VerifyCode verifyCode) {
        QueryWrapper<SmsVerifyCodeInfo> smsVerifyCodeInfoQuery = new QueryWrapper<>();
        smsVerifyCodeInfoQuery.eq("phone_number", phoneNumber.getValue())
                .eq("verify_code", verifyCode.getValue())
                .gt("expiration_time", LocalDateTime.now());
        return smsVerifyCodeInfoMapper.selectOne(smsVerifyCodeInfoQuery);
    }

    public static int genVerifyCode() {
        Random rand = new Random();
        return rand.nextInt((999999 - 100000) + 1) + 100000;
    }


}
